package com.me.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

/**
 * 基于 java.net.URLConnection 的 简单 HTTP请求工具类
 *
 * @author ME
 * @date 2020/3/10
 */
public class SimpleHttpUtil {

    public static void main(String[] args) {
        System.out.println(SimpleHttpUtil.doGet("http://www.baidu.com"));
    }

    public static String doGet(String url) {
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine;
        try {
            URL localURL = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) localURL.openConnection();

            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            if (conn.getResponseCode() >= 300) {
                throw new RuntimeException("HTTP Request is not success, Response code is " + conn.getResponseCode());
            }
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultBuffer.toString();
    }

    public static String doPost(String postUrl, Map<String, String> params) {
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        // 返回结果
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        try {
            URL localURL = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) localURL.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            String postData = map2UrlParam(params);
            conn.setRequestProperty("Content-Length", String.valueOf(postData.length()));
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();

            //获取响应状态
            if (conn.getResponseCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
                throw new RuntimeException("HTTP Request is not success, Response code is " + conn.getResponseCode());
            }

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultBuffer.toString();
    }

    public static String map2UrlParam(Map<String, String> params) {
        StringBuilder postData = new StringBuilder();
        // for (Map.Entry<String, String> entry : params.entrySet()) {
        //     postData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        // }
        params.forEach((key, value) -> {
            postData.append(key).append("=").append(value).append("&");
        });
        return StringUtils.substringBeforeLast(postData.toString(), "&");
    }
}
